from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse

from taggit.managers import TaggableManager


class PublishManger(models.Manager):
    def get_query(self):
        return super(PublishManger, self).get_queryset().filter(status='published')


class Post(models.Model):
    objects = models.Manager()
    published = PublishManger()
    tags = TaggableManager()
    STATUS_CHOICE = {
        ('draft', 'Draft'),
        ('published', 'Published'),
    }
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=250, verbose_name='标题')
    slug = models.SlugField(max_length=250, unique_for_date='publish')
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts', verbose_name='作者')
    body = models.TextField(verbose_name='内容')
    publish = models.DateTimeField(default=timezone.now, verbose_name='出版日期')
    created = models.DateTimeField(auto_now_add=True, verbose_name='创建日期')
    updated = models.DateTimeField(auto_now_add=True, verbose_name='更新日期')
    status = models.CharField(choices=STATUS_CHOICE, verbose_name='状态', max_length=250)

    class Meta:
        ordering = ('-publish',)
        verbose_name_plural = verbose_name = '文章'

    def __str__(self):
        return "{}".format(self.title)

    def get_absolute_url(self):
        return reverse('detail', args=[self.id])


class Comments(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
    name = models.CharField(max_length=80)
    email = models.EmailField()
    body = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    update = models.DateTimeField(auto_now_add=True)
    activate = models.BooleanField(default=False)

    class Meta:
        ordering = ['created', ]
        verbose_name_plural = verbose_name = '评论'

    def __str__(self):
        return 'comment by {} on {}'.format(self.name, self.post)
# Create your models here.
